<?php

class CpvatController extends Core_Controller_Action 
{
	private $_vat;
	
	public function init() {
	
		$this->_vat = new Vat();
	}
	
	public function indexAction() {
		$this->_forward( 'list', 'cpvat' );
	}
	
	public function itemAction() {
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		
		if( $this->_request->isPost() ) {
		
			$post = $this->_request->getPost();

			if( ( strlen( $post['rate'] ) == 0 ) && empty( $post['rate'] ) ) {
				$this->view->err_rate = 'Podaj stawkę';
			} else {

				if( $id ) {
					$item = $this->_vat->getItem( $id )->getFirst();
					foreach( $post as $key => $value ) {
	
						if( strlen( $value ) > 0 ) {
							$item->{$key} = $value;
						}
					}
					$item->save();

					$this->_redirect( 'cpvat/list/oper/2' );
				} else {
					foreach( $post as $key => $value ) {
	
						if( strlen( $value ) > 0 ) {
							$this->_vat->{$key} = $value;
						}
					}
					$this->_vat->save();
					
					$this->_redirect( 'cpvat/list/oper/1' );
				}
			}

		} else {
			if( $id ) {
				$item = $this->_vat->getItem( $id )->toArray();

				foreach( $item[0] as $key => $value ) {
	
					$this->view->{$key} = $value;
				}
			}
		
		}
		
		$this->assignType( 0 );
	}
	
	public function listAction() {
		$page = intval( $this->_request->getParam( 'page', 1 ) );
		
		$pagerLayout = $this->_vat->getListWithPager( $page, $this->view->baseUrl() );
		
		$this->view->list = $pagerLayout->execute();
		$this->view->pager = $pagerLayout;
		
		
		$this->assignType( 0 );
	}
	
	public function deleteAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender();
		
		$type = intval( $this->_request->getParam( 'type', 0 ) );
		$id = intval( $this->_request->getParam( 'id', 0 ) );
		
		if( $id > 0 ) {
			$this->_vat->deleteItem( $id );
			
			$this->_redirect( 'cpvat/list/oper/4' );
		} else {
			$this->_redirect( 'cpvat/list/oper/3' );
		}
	}
	
	public function assignType( $type ) {
		
		$this->view->type = $type;
		
		switch( $type ) {
			case 0 :
				$this->view->yih2 = 'Vat';
				break;
		}
	}
}